package zcw.com.lib_leet_code;

import zcw.com.lib_leet_code.bean.ListNode;
import zcw.com.lib_leet_code.util.Util;

/**
 * Created by 朱城委 on 2021/9/6.<br><br>
 *
 * 中等：分隔链表
 */
public class Topic86 {

    public static void main(String[] args) {
        Topic86 instance = new Topic86();

        int[] array = new int[] {1,4,3,2,5,2};
        ListNode head = Util.createList(array);
        Util.printList(instance.partition(head, 3));

        array = new int[] {2,1};
        head = Util.createList(array);
        Util.printList(instance.partition(head, 2));

        array = new int[] {};
        head = Util.createList(array);
        Util.printList(instance.partition(head, 0));

        array = new int[] {1};
        head = Util.createList(array);
        Util.printList(instance.partition(head, 2));
    }

    public ListNode partition(ListNode head, int x) {
        ListNode start = new ListNode(0);
        start.next = head;
        ListNode pre = start;

        while (pre.next != null) {
            if(pre.next.val >= x) {
                break;
            }

            pre = pre.next;
        }

        if(pre.next == null) {
            return head;
        }

        ListNode curr = pre.next;
        while (curr.next != null) {
            if(curr.next.val < x) {
                ListNode temp = curr.next;
                curr.next = curr.next.next;

                temp.next = pre.next;
                pre.next = temp;
                pre = pre.next;
            }
            else {
                curr = curr.next;
            }
        }

        return start.next;
    }
}
